package com.loan.util;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import com.jfinal.kit.PathKit;

public class FileUtil {

    public static String upload(File source) throws IOException {
    	return upload(source,false);
    }
    
    public static String upload(File source, boolean reduce) throws IOException {
    	String fileName = source.getName();
        Date now = new Date();
        String year = new SimpleDateFormat("yyyy").format(now);
        String month = new SimpleDateFormat("MM").format(now);
        String extension = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        String prefix;
        if("png".equalsIgnoreCase(extension) || "jpg".equalsIgnoreCase(extension) || "gif".equalsIgnoreCase(extension) || "jpeg".equalsIgnoreCase(extension)){
            prefix = "image";
            fileName = generateWord() + "." + extension;
        }else{
            prefix = "file";
        }
        FileInputStream fis = new FileInputStream(source);
        String path = "/attachment/" + prefix + "/" + year+"/"+month;
        if(reduce) {
        	reduceImg(source, PathKit.getWebRootPath()+path+"/"+fileName, extension, 0.9);
        }else {
            File targetDir = new File(PathKit.getWebRootPath() + path);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File target = new File(targetDir,fileName);
            if (!target.exists()) {
                target.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(target);
            byte[] bts = new byte[300];
            while (fis.read(bts, 0, 300) != -1) {
                fos.write(bts, 0, 300);
            }
            fos.close();
            fis.close();
            source.delete();
        }
        return path + "/" + fileName;
    }

	
	/** 
     * 采用指定宽度、高度或压缩比例 的方式对图片进行压缩 
     * @param imgsrc 源图片地址 
     * @param imgdist 目标图片地址 
     * @param widthdist 压缩后图片宽度（当rate==null时，必传） 
     * @param heightdist 压缩后图片高度（当rate==null时，必传） 
     * @param rate 压缩比例  
     */  
    public static void reduceImg(File file, String imgdist, String extension, double rate) {  
        try {  
            // 检查文件是否存在  
            if (!file.exists()) {  
                return;  
            }  
            // 如果rate不为空说明是按比例压缩
            int widthdist = 0;
            int heightdist = 0;
            if (rate > 0) {  
                int results[] = { 0, 0 };  
                // 获取文件高度和宽度  
            	InputStream is = null;  
                BufferedImage src = null;  
                try {  
                    is = new FileInputStream(file);  
                    src = javax.imageio.ImageIO.read(is);  
                    results[0] = src.getWidth(null); // 得到源图宽  
                    results[1] = src.getHeight(null); // 得到源图高  
                    is.close();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
                if (results == null || results[0] == 0 || results[1] == 0) {  
                    return;  
                } else {  
                    widthdist = (int) (results[0] * rate);  
                    heightdist = (int) (results[1] * rate);  
                }  
            }  
            // 开始读取文件并进行压缩  
            Image src = javax.imageio.ImageIO.read(file);  
            BufferedImage tag = new BufferedImage((int) widthdist,  
                    (int) heightdist, BufferedImage.TYPE_INT_RGB);  
  
            tag.getGraphics().drawImage(  
                    src.getScaledInstance(widthdist, heightdist,  
                            Image.SCALE_SMOOTH), 0, 0, null);  

            FileOutputStream out = new FileOutputStream(imgdist);  
            ImageIO.write(tag, extension, out);
            //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
            //encoder.encode(tag);  
            //out.close();  
        } catch (IOException ex) {  
            ex.printStackTrace();  
        }
    } 
    
    private static String generateWord() {
        String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",
                "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
                "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z" };
        List<String> list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        String result = afterShuffle.substring(5, 9);
        return result;
    }
    
    public static String download(String urlPath) throws Exception {
        // 构造URL
        URL url = new URL(urlPath);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5*1000);
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf=new File("/opt/apache-tomcat-9.0.8/webapps/ROOT/attachment/cert/");
        if(!sf.exists()){
            sf.mkdirs();
        }
        // int randomNo=(int)(Math.random()*1000000);
        // String filename=urlPath.substring(urlPath.lastIndexOf("/")+1,urlPath.length());//获取服务器上图片的名称
        // filename = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())+randomNo+filename;//时间+随机数防止重复
        String filename = DateUtil.getTimeStamp()+".jpg";
        OutputStream os = new FileOutputStream(sf.getPath()+"/"+filename);
        String virtualPath="/attachment/cert/"+filename;//存入数据库的虚拟路径
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
        return virtualPath;
    }
}
